package com.useeinfo.asg.common.utils;

import com.xiaoleilu.hutool.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by tgq on 2017/2/25.
 */
public class WxMessage {


    public static void main(String[] args) {
       System.out.println(getTicket(getToken("wx2d27180b0a6a3790", "4a1e53612b94cc59cd3dfe3f34d2efec")));
        System.out.println(create_nonce_str());
        System.out.println(create_timestamp());
        System.out.println(getResult(getTicket(getToken("wx2d27180b0a6a3790", "4a1e53612b94cc59cd3dfe3f34d2efec")),
                "http://ad.tnbchina.com/asg/mobile/wxShare/wxshare2.action"));

// String jsapi_ticket = "kgt8ON7yVITDhtdwci0qecRXz9HyXuyXgIslzmd3ri0s5EnLrVZZfrPJotRfKWQ-TTuQ2ZMAK86GUlWF1PHhcg";
    };

    public static Map<String, String> getResult(String ticket,String url){

        Map<String, String> ret = sign(ticket, url);
        return ret;
    }


    public static String getToken(String appid,String secret){

        String accessToken = "";
        String result="";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        HttpsURLConnection httpsURLConnection = null;
        try {
            URL url1 = new URL(url);
            httpsURLConnection = (HttpsURLConnection)url1.openConnection();
            httpsURLConnection.setDoOutput(true);
            httpsURLConnection.setDoInput(true);
            httpsURLConnection.setRequestProperty("Charsert", "UTF-8");
            httpsURLConnection.setRequestProperty("Content-Type","text/xml");
            httpsURLConnection.setRequestProperty("Content-length", "0");
            // httpconn.setConnectTimeout(300 * 1000);
            httpsURLConnection.setRequestMethod("POST");
            httpsURLConnection.connect();
            DataOutputStream out = new DataOutputStream(httpsURLConnection
                    .getOutputStream());
           // out.writeBytes(parameter);
            out.flush();
            out.close();
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    httpsURLConnection.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = rd.readLine()) != null)
                result += line;
        }catch (Exception e){
            e.printStackTrace();
        }
        if(!CommUtil.null2String(result).equals("")) {
            JSONObject json = new JSONObject(result);
            accessToken = json.getString("access_token");
        }
        return accessToken;
    }

    public static String getTicket(String access_token){

        String ticket = "";
        String result="";
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";

        HttpsURLConnection httpsURLConnection = null;
        try {
            URL url1 = new URL(url);
            httpsURLConnection = (HttpsURLConnection)url1.openConnection();
            httpsURLConnection.setDoOutput(true);
            httpsURLConnection.setDoInput(true);
            httpsURLConnection.setRequestProperty("Charsert", "UTF-8");
            httpsURLConnection.setRequestProperty("Content-Type","text/xml");
            httpsURLConnection.setRequestProperty("Content-length", "0");
            // httpconn.setConnectTimeout(300 * 1000);
            httpsURLConnection.setRequestMethod("POST");
            httpsURLConnection.connect();
            DataOutputStream out = new DataOutputStream(httpsURLConnection
                    .getOutputStream());
            out.flush();
            out.close();
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    httpsURLConnection.getInputStream(), "UTF-8"));
            String line = "";
            while ((line = rd.readLine()) != null)
                result += line;
        }catch (Exception e){
            e.printStackTrace();
        }
        if(!CommUtil.null2String(result).equals("")) {
            JSONObject json = new JSONObject(result);
            ticket = json.getString("ticket");
        }
        return ticket;
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

//注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    public static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    public static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
